import type { Bill, RoomState, StatisticsReport, RoomStatistics } from '../types';
import { FanSpeed } from '../types';

/**
 * 计费服务
 * 负责生成账单、详单和统计报表
 */
export class BillingService {
  private bills: Map<string, Bill> = new Map();
  private allRecords: Bill[] = []; // 所有历史账单

  /**
   * 生成账单
   */
  generateBill(roomState: RoomState, checkInTime: number, checkOutTime: number): Bill {
    const bill: Bill = {
      roomId: roomState.roomId,
      checkInTime,
      checkOutTime,
      totalCost: roomState.totalCost,
      totalPowerConsumption: roomState.totalPowerConsumption,
      totalServiceDuration: this.calculateTotalDuration(roomState),
      detailRecords: [...roomState.detailRecords]
    };

    this.bills.set(roomState.roomId, bill);
    this.allRecords.push(bill);

    return bill;
  }

  /**
   * 计算总服务时长
   */
  private calculateTotalDuration(roomState: RoomState): number {
    return roomState.detailRecords
      .filter(record => record.duration > 0)
      .reduce((total, record) => total + record.duration, 0);
  }

  /**
   * 获取账单
   */
  getBill(roomId: string): Bill | null {
    return this.bills.get(roomId) || null;
  }

  /**
   * 生成统计报表
   */
  generateStatisticsReport(startTime: number, endTime: number): StatisticsReport {
    // 筛选指定时间范围内的账单
    const filteredBills = this.allRecords.filter(
      bill => bill.checkInTime >= startTime && bill.checkOutTime <= endTime
    );

    if (filteredBills.length === 0) {
      return {
        startTime,
        endTime,
        totalRooms: 0,
        totalServiceRequests: 0,
        totalCost: 0,
        totalPowerConsumption: 0,
        averageCostPerRoom: 0,
        roomStatistics: [],
        fanSpeedDistribution: {
          low: 0,
          medium: 0,
          high: 0
        }
      };
    }

    // 计算总计数据
    const totalRooms = new Set(filteredBills.map(b => b.roomId)).size;
    const totalCost = filteredBills.reduce((sum, b) => sum + b.totalCost, 0);
    const totalPowerConsumption = filteredBills.reduce((sum, b) => sum + b.totalPowerConsumption, 0);
    
    // 计算服务请求总数
    const totalServiceRequests = filteredBills.reduce(
      (sum, b) => sum + b.detailRecords.filter(r => r.action.includes('开始送风')).length,
      0
    );

    // 按房间统计
    const roomStatsMap = new Map<string, RoomStatistics>();
    
    filteredBills.forEach(bill => {
      const existing = roomStatsMap.get(bill.roomId);
      
      if (existing) {
        existing.serviceCount += bill.detailRecords.filter(r => r.action.includes('开始送风')).length;
        existing.totalCost += bill.totalCost;
        existing.totalPowerConsumption += bill.totalPowerConsumption;
        existing.totalServiceDuration += bill.totalServiceDuration;
      } else {
        const serviceRecords = bill.detailRecords.filter(r => r.currentTemp > 0);
        const avgTemp = serviceRecords.length > 0
          ? serviceRecords.reduce((sum, r) => sum + r.currentTemp, 0) / serviceRecords.length
          : 0;
        
        const mostUsedFanSpeed = this.getMostUsedFanSpeed(bill);

        roomStatsMap.set(bill.roomId, {
          roomId: bill.roomId,
          serviceCount: bill.detailRecords.filter(r => r.action.includes('开始送风')).length,
          totalCost: bill.totalCost,
          totalPowerConsumption: bill.totalPowerConsumption,
          totalServiceDuration: bill.totalServiceDuration,
          averageTemp: avgTemp,
          mostUsedFanSpeed
        });
      }
    });

    // 统计风速分布
    const fanSpeedDistribution = {
      low: 0,
      medium: 0,
      high: 0
    };

    filteredBills.forEach(bill => {
      bill.detailRecords.forEach(record => {
        if (record.fanSpeed) {
          fanSpeedDistribution[record.fanSpeed]++;
        }
      });
    });

    return {
      startTime,
      endTime,
      totalRooms,
      totalServiceRequests,
      totalCost,
      totalPowerConsumption,
      averageCostPerRoom: totalCost / totalRooms,
      roomStatistics: Array.from(roomStatsMap.values()),
      fanSpeedDistribution
    };
  }

  /**
   * 获取最常使用的风速
   */
  private getMostUsedFanSpeed(bill: Bill): FanSpeed {
    const speedCount: Record<FanSpeed, number> = {
      [FanSpeed.LOW]: 0,
      [FanSpeed.MEDIUM]: 0,
      [FanSpeed.HIGH]: 0
    };

    bill.detailRecords.forEach(record => {
      if (record.fanSpeed) {
        speedCount[record.fanSpeed] += record.duration;
      }
    });

    let maxSpeed: FanSpeed = FanSpeed.MEDIUM;
    let maxDuration = 0;

    (Object.entries(speedCount) as [FanSpeed, number][]).forEach(([speed, duration]) => {
      if (duration > maxDuration) {
        maxDuration = duration;
        maxSpeed = speed;
      }
    });

    return maxSpeed;
  }

  /**
   * 获取所有账单
   */
  getAllBills(): Bill[] {
    return [...this.allRecords];
  }

  /**
   * 清除账单
   */
  clearBill(roomId: string): void {
    this.bills.delete(roomId);
  }

  /**
   * 格式化账单为文本
   */
  formatBillText(bill: Bill): string {
    const lines: string[] = [];
    
    lines.push('=================================');
    lines.push('        空调使用账单');
    lines.push('=================================');
    lines.push(`房间号: ${bill.roomId}`);
    lines.push(`入住时间: ${new Date(bill.checkInTime).toLocaleString()}`);
    lines.push(`退房时间: ${new Date(bill.checkOutTime).toLocaleString()}`);
    lines.push('---------------------------------');
    lines.push(`总耗电量: ${bill.totalPowerConsumption.toFixed(2)} 度`);
    lines.push(`总费用: ¥${bill.totalCost.toFixed(2)}`);
    lines.push(`服务时长: ${this.formatDuration(bill.totalServiceDuration)}`);
    lines.push('=================================');
    lines.push('');
    lines.push('详细记录:');
    lines.push('---------------------------------');
    
    bill.detailRecords.forEach((record, index) => {
      lines.push(`${index + 1}. ${new Date(record.timestamp).toLocaleString()}`);
      lines.push(`   操作: ${record.action}`);
      lines.push(`   当前温度: ${record.currentTemp.toFixed(1)}°C`);
      if (record.duration > 0) {
        lines.push(`   耗电: ${record.powerConsumption.toFixed(3)} 度`);
        lines.push(`   费用: ¥${record.cost.toFixed(2)}`);
        lines.push(`   时长: ${this.formatDuration(record.duration)}`);
      }
      lines.push('');
    });
    
    return lines.join('\n');
  }

  /**
   * 格式化时长
   */
  private formatDuration(seconds: number): string {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;
    
    if (hours > 0) {
      return `${hours}小时${minutes}分钟${secs}秒`;
    } else if (minutes > 0) {
      return `${minutes}分钟${secs}秒`;
    } else {
      return `${secs}秒`;
    }
  }

  /**
   * 格式化统计报表为文本
   */
  formatStatisticsText(report: StatisticsReport): string {
    const lines: string[] = [];
    
    lines.push('=================================');
    lines.push('        统计报表');
    lines.push('=================================');
    lines.push(`时间范围: ${new Date(report.startTime).toLocaleString()}`);
    lines.push(`       至 ${new Date(report.endTime).toLocaleString()}`);
    lines.push('---------------------------------');
    lines.push(`总房间数: ${report.totalRooms}`);
    lines.push(`服务请求总数: ${report.totalServiceRequests}`);
    lines.push(`总费用: ¥${report.totalCost.toFixed(2)}`);
    lines.push(`总耗电量: ${report.totalPowerConsumption.toFixed(2)} 度`);
    lines.push(`平均费用/房间: ¥${report.averageCostPerRoom.toFixed(2)}`);
    lines.push('---------------------------------');
    lines.push('风速使用分布:');
    lines.push(`  高风: ${report.fanSpeedDistribution.high} 次`);
    lines.push(`  中风: ${report.fanSpeedDistribution.medium} 次`);
    lines.push(`  低风: ${report.fanSpeedDistribution.low} 次`);
    lines.push('=================================');
    lines.push('');
    lines.push('房间明细:');
    lines.push('---------------------------------');
    
    report.roomStatistics.forEach((roomStat, index) => {
      lines.push(`${index + 1}. 房间 ${roomStat.roomId}`);
      lines.push(`   服务次数: ${roomStat.serviceCount}`);
      lines.push(`   总费用: ¥${roomStat.totalCost.toFixed(2)}`);
      lines.push(`   总耗电: ${roomStat.totalPowerConsumption.toFixed(2)} 度`);
      lines.push(`   平均温度: ${roomStat.averageTemp.toFixed(1)}°C`);
      lines.push(`   常用风速: ${roomStat.mostUsedFanSpeed}`);
      lines.push('');
    });
    
    return lines.join('\n');
  }
}

